import React, { useState } from 'react';
import { Button, Input, Card } from 'antd';

const StreamTest: React.FC = () => {
  const [messages, setMessages] = useState<string[]>([]);
  const [inputValue, setInputValue] = useState('');
  const [isStreaming, setIsStreaming] = useState(false);

  const testStreamMessage = async () => {
    if (!inputValue.trim()) return;
    
    setIsStreaming(true);
    setMessages(prev => [...prev, `用户: ${inputValue}`]);
    
    try {
      const response = await fetch('https://ai.hzailab.cn/v1/conversation/completion', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          'Authorization': 'IjMzNTQ2ODc2NTM0MDExZjBiZmU5MGUxNjIxNWM4NjI0Ig.aF5wLQ.Vw5fh2bmG9A9SVvFmNwveXGFKG8',
        },
        body: JSON.stringify({
          "conversation_id": "318a616a46a911f0b84616f96a0dee16",
          "messages": [
            {
              "content": "你好！ 我是你的助理，有什么可以帮到你的吗？",
              "id": "9bd30aa9-7b0a-419d-aa40-cb1bfb34e085",
              "role": "assistant"
            },
            {
              "id": "test-user-message",
              "content": inputValue,
              "role": "user",
              "doc_ids": []
            }
          ]
        }),
      });

      if (!response.ok) {
        throw new Error(`HTTP error! status: ${response.status}`);
      }

      const reader = response.body?.getReader();
      if (!reader) {
        throw new Error('无法获取响应流');
      }

      let buffer = '';
      let currentAnswer = '';
      const decoder = new TextDecoder();

      // 添加助手消息占位符
      setMessages(prev => [...prev, '助手: ']);

      while (true) {
        const { done, value } = await reader.read();
        
        if (done) {
          console.log('✅ 流式响应完成');
          break;
        }

        const chunk = decoder.decode(value, { stream: true });
        buffer += chunk;
        
        // 处理缓冲区中的完整行
        const lines = buffer.split('\n');
        buffer = lines.pop() || '';
        
        for (const line of lines) {
          if (!line.trim() || !line.startsWith('data:')) {
            continue;
          }
          
          const jsonStr = line.substring(5).trim();
          if (!jsonStr) {
            continue;
          }
          
          try {
            const parsed = JSON.parse(jsonStr);
            console.log('📨 解析到数据:', parsed);
            
            if (parsed.data && parsed.data.answer) {
              currentAnswer = parsed.data.answer;
              console.log('✅ 更新内容:', currentAnswer.substring(0, 100) + '...');
              
              // 更新最后一条消息（助手回复）
              setMessages(prev => {
                const newMessages = [...prev];
                newMessages[newMessages.length - 1] = `助手: ${currentAnswer}`;
                return newMessages;
              });
            }
          } catch (e) {
            console.warn('❌ JSON解析失败:', jsonStr.substring(0, 50) + '...', e);
          }
        }
      }

    } catch (error: any) {
      console.error('❌ 流式请求失败:', error);
      setMessages(prev => [...prev, `错误: ${error?.message || '未知错误'}`]);
    } finally {
      setIsStreaming(false);
      setInputValue('');
    }
  };

  return (
    <Card title="流式消息测试" style={{ margin: '20px', maxWidth: '800px' }}>
      <div style={{ marginBottom: '20px' }}>
        <Input.Group compact>
          <Input
            style={{ width: 'calc(100% - 100px)' }}
            value={inputValue}
            onChange={(e) => setInputValue(e.target.value)}
            placeholder="输入测试消息..."
            onPressEnter={testStreamMessage}
            disabled={isStreaming}
          />
          <Button 
            type="primary" 
            onClick={testStreamMessage}
            loading={isStreaming}
            disabled={!inputValue.trim()}
          >
            {isStreaming ? '发送中...' : '发送'}
          </Button>
        </Input.Group>
      </div>
      
      <div style={{ 
        height: '400px', 
        overflowY: 'auto', 
        border: '1px solid #d9d9d9', 
        padding: '10px',
        backgroundColor: '#fafafa'
      }}>
        {messages.map((msg, index) => (
          <div key={index} style={{ marginBottom: '10px', padding: '5px' }}>
            <div style={{ 
              whiteSpace: 'pre-wrap',
              fontFamily: 'monospace',
              fontSize: '14px'
            }}>
              {msg}
            </div>
          </div>
        ))}
        
        {messages.length === 0 && (
          <div style={{ textAlign: 'center', color: '#999', marginTop: '50px' }}>
            输入消息开始测试流式传输...
          </div>
        )}
      </div>
    </Card>
  );
};

export default StreamTest; 